import { Statistic, Col, Row, Card } from "antd";
import React, { useEffect, useState } from "react";
import { Bar, Line } from '@ant-design/charts';
import { OrderSummaryItem, SalesSummaryItem, TopNItem } from "@/types/chart";
import { merchantService } from "@/service/merchantService";



const Dashboard: React.FC = () => {

  const [orderSummaryData, setOrderSummaryData] = useState<OrderSummaryItem[]>([]);
  const [salesSummaryData, setSalesSummaryData] = useState<SalesSummaryItem[]>([]);
  const [topNData, setTopNData] = useState<TopNItem[]>([]);


  const orderSummaryConfig = {
    data: orderSummaryData,
    height: 400,
    xField: 'date',
    yField: 'totalOrders',
  };  

  const salesSummaryConfig = {
    data: salesSummaryData,
    height: 400,
    xField: 'date',
    yField: 'totalSales',
  };

  const topNConfig = {
    data: topNData,
    height: 400,
    xField: 'totalSales',
    yField: 'spuName',
    colorField: 'rank', // 渐变色
    legend: false,
    barStyle: { radius: [4, 4, 0, 0] }, // 柔和圆角
    label: { position: 'right' },
  };


   const data = [
    { year: '1991', value: 3 },
    { year: '1992', value: 4 },
    { year: '1993', value: 3.5 },
    { year: '1994', value: 5 },
    { year: '1995', value: 4.9 },
    { year: '1996', value: 6 },
    { year: '1997', value: 7 },
    { year: '1998', value: 9 },
    { year: '1999', value: 13 },
  ];

  const config = {
    data,
    height: 400,
    xField: 'year',
    yField: 'value',
  };  

  useEffect(() => {
    const fetchData = async () => {
      const [orderSummary, topN] = await Promise.all([
        merchantService.weeklyOrderSummary(),
        merchantService.top10Products(),
      ]);
      if (orderSummary) {
        setOrderSummaryData(orderSummary);
      }
      if (topN) {
        setTopNData(topN);
      }
    };
    fetchData();
    const timer = setInterval(fetchData, 1000 * 5); // 每5秒刷新一次数据
    return () => clearInterval(timer); // 清理定时器
  }, []);


  return (
    <div style={{ padding: '20px' }}>
      <Row gutter={16}>
        <Col span={12}>
          <Card className="flex items-center justify-center">
            <Statistic title="总订单数" value={1128} style={{ marginBottom: '20px' }} />
          </Card>
        </Col>
        <Col span={12}>
          <Card className="flex items-center justify-center">
            <Statistic title="总销售额" value={9344} prefix="¥" style={{ marginBottom: '20px' }} />
          </Card>
        </Col>
      </Row>


      {/* 七日下单数折线图*/}
      <Line {...orderSummaryConfig} />

      {/* 七日销售额折线图 */}

      {/* 七日内spu热度排行 */}
      <Bar {...topNConfig} />


    </div>
  );
}


export default Dashboard;